package com.shandao.shangxiu.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.TextView;

import com.shandao.shangxiu.R;

/**
 * 添加了foot加载更多listView
 * @author king
 */
public class LoadListView extends ListView implements OnScrollListener {
	View footer;
	int firstVisibleItem; // 当前第一个可见Item的位置
	IReflashListener iReflashListener;
	int totalItemCount;
	int lastVisibleItem;
	boolean isLoading; // 正在加载
	private TextView txtViewLoading = null;

	public LoadListView(Context context) {
		super(context);
		initView(context);
	}

	public LoadListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public LoadListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	// 初始化界面，添加顶部布局至ListView
	public void initView(Context context) {
		LayoutInflater inflater = LayoutInflater.from(context);
		footer = inflater.inflate(R.layout.listview_footer, null);
		footer.findViewById(R.id.listView_footer).setVisibility(View.GONE);
		this.addFooterView(footer);
		this.setOnScrollListener(this);
		txtViewLoading = (TextView) footer.findViewById(R.id.foot_more);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.firstVisibleItem = firstVisibleItem;
		this.totalItemCount = totalItemCount;
		this.lastVisibleItem = firstVisibleItem + visibleItemCount;

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (totalItemCount == lastVisibleItem
				&& scrollState == SCROLL_STATE_IDLE) {
			if (!isLoading) {
				isLoading = true;
				footer.findViewById(R.id.listView_footer).setVisibility(
						View.VISIBLE);
				iReflashListener.onLoad();
			}
		}

	}

	public void loadingComplete() {
		isLoading = false;
		footer.findViewById(R.id.listView_footer).setVisibility(View.GONE);
	}

	public void allDataLoadingComplete() {
		isLoading = false;
		txtViewLoading.setText("全部数据已经加载完成");
		footer.setVisibility(View.GONE);
	}

	public void setInterfacs(IReflashListener iReflashListener) {
		this.iReflashListener = iReflashListener;
	}

	public interface IReflashListener {
		public void onLoad();
	}
}